package com.yjz.study.ui.fragment

import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.yjz.common.base.BaseFragment
import com.yjz.common.extend.getResColor
import com.yjz.common.extend.loadCorner
import com.yjz.common.extend.loadCircle
import com.yjz.common.restful.CallBack
import com.yjz.common.restful.HttpBaseResponse
import com.yjz.log.util.DisplayUtil
import com.yjz.study.R
import com.yjz.study.account.AccountManager
import com.yjz.study.arouter.ARouterLogic
import com.yjz.study.arouter.navigation
import com.yjz.study.http.ApiFactory
import com.yjz.study.http.api.AccountApi
import com.yjz.study.http.entity.res.CourseNotice
import com.yjz.study.http.entity.res.Notice
import com.yjz.study.http.entity.res.UserProfile
import com.yjz.ui.banner.BannerLayout
import com.yjz.ui.banner.core.BannerAdapter
import com.yjz.ui.banner.core.BannerModel

/**
 *作用 : 我的
 *作者 : yjz
 *时间 : 2025/2/14 16:04
 */
class ProfileFragment : BaseFragment() {

    companion object {
        const val REQUEST_CODE_LOGIN_PROFILE = 1001
    }

    private var notifyCountTv: TextView? = null
    private var userNameTv: TextView? = null
    private var loginDescTv: TextView? = null
    private var avatarImg: ImageView? = null
    private var banner: BannerLayout? = null
    private var collection: TextView? = null
    private var history: TextView? = null
    private var learn: TextView? = null

    override fun getLayoutId(): Int {
        return R.layout.fragment_mine
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        notifyCountTv = view.findViewById(R.id.notify_count)

        avatarImg = view.findViewById(R.id.user_avatar)
        userNameTv = view.findViewById(R.id.user_name)
        loginDescTv = view.findViewById(R.id.login_desc)
        banner = view.findViewById(R.id.banner)

        collection = view.findViewById(R.id.tab_item_collection)
        history = view.findViewById(R.id.tab_item_history)
        view.findViewById<LinearLayout>(R.id.course_notice_ll).setOnClickListener {
            ARouterLogic.navigation(ARouterLogic.Path.NOTICE)
        }
        learn = view.findViewById(R.id.tab_item_learn)

        queryCourseNotice()
        queryLoginUserData()
    }

    private fun queryCourseNotice() {
        ApiFactory.create(AccountApi::class.java).notice()
            .enqueue(object : CallBack<CourseNotice> {
                override fun onSuccess(response: HttpBaseResponse<CourseNotice>) {
                    if (response.data != null && response.data!!.total > 0) {
                        notifyCountTv?.text = response.data!!.total.toString()
                        notifyCountTv?.visibility = View.VISIBLE
                    }
                }

                override fun onFailed(throwable: Throwable) {

                }
            })
    }

    private fun queryLoginUserData() {
        if (AccountManager.isLogin()) {
            AccountManager.getUserProfile(this, { userProfile ->
                if (userProfile != null) {
                    updateUI(userProfile)
                }
            }, true)
        } else {
            AccountManager.login(context = context) { success ->
                if (success) {
                    AccountManager.getUserProfile(this, { userProfile ->
                        if (userProfile != null) {
                            updateUI(userProfile)
                        }
                    }, false)
                }
            }
        }
    }

    private fun updateUI(userProfile: UserProfile) {
        userNameTv?.text = if (userProfile.isLogin) userProfile.userName else getString(R.string.profile_not_login)
        loginDescTv?.text = if (userProfile.isLogin) getString(R.string.profile_login_desc_welcome_back) else getString(
            R.string.profile_login_desc
        )
        if (userProfile.isLogin) {
            //avatar 需要判断空
            if (TextUtils.isEmpty(userProfile.avatar)) {
                avatarImg?.setImageResource(R.drawable.ic_avatar_default)
            } else {
                avatarImg?.loadCircle(userProfile.avatar)
            }
        } else {
            avatarImg?.setImageResource(R.drawable.ic_avatar_default)
            userNameTv?.setOnClickListener {
                navigation(
                    ARouterLogic.Path.LOGIN_PATH,
                    requestCode = REQUEST_CODE_LOGIN_PROFILE
                )
            }
        }

        collection?.text = spannableTabItem(userProfile.favoriteCount, getString(R.string.profile_tab_item_collection))
        history?.text = spannableTabItem(userProfile.browseCount, getString(R.string.profile_tab_item_history))
        learn?.text = spannableTabItem(userProfile.learnMinutes, getString(R.string.profile_tab_item_learn))

        updateBanner(userProfile.bannerNoticeList)
    }

    private fun updateBanner(bannerNoticeList: List<Notice>?) {
        if (bannerNoticeList.isNullOrEmpty()) return
        val models = mutableListOf<BannerModel>()
        bannerNoticeList.forEach {
            models.add(BannerModel(it.cover))
        }
        banner?.setIntervalTime(2000)
        banner?.setOnBannerClickListener { _, _, position ->
            ARouterLogic.startActivity4Browser(bannerNoticeList[position].url)
        }
        banner?.setBindAdapter { viewHolder: BannerAdapter.ViewHolder, mo: BannerModel, position: Int ->
            // if (viewHolder == null || mo == null) return@setBindAdapter
            val imageView = viewHolder.findViewById<ImageView>(R.id.iv_image)
            imageView.loadCorner(mo.url, DisplayUtil.dp2px(10f, resources))
        }
        banner?.setBannerData(models)
        banner?.visibility = View.VISIBLE
    }

    private fun spannableTabItem(topText: Int, bottomText: String): String {
        val spanStr = topText.toString()
        val ssb = SpannableStringBuilder()
        val ssTop = SpannableString(spanStr)
        val spanFlag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        ssTop.setSpan(
            ForegroundColorSpan(getResColor(com.yjz.ui.R.color.color_000)),
            0,
            ssTop.length,
            spanFlag
        )
        ssTop.setSpan(AbsoluteSizeSpan(18, true), 0, ssTop.length, spanFlag)
        ssTop.setSpan(StyleSpan(Typeface.BOLD), 0, ssTop.length, spanFlag)
        ssb.append(ssTop)
        ssb.append(bottomText)
        return ssb.toString()
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == REQUEST_CODE_LOGIN_PROFILE && resultCode == Activity.RESULT_OK && data != null) {
//            queryLoginUserData()
//        }
//    }
}